import {reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout} from '@/api';

export default {
    namespaced: true,
    state: {
        code: '',
        token: sessionStorage.getItem('TOKEN'),
        userInfo:{},
    },
    actions: {
        //获取验证码
        async getCode(context, phone){
            let result = await reqGetCode(phone)
            if(result.code == 200){
                context.commit('GETCODE', result.data)
                return 'ok'
            }else{
                return Promise.reject(new Error('failed'))
            }
        },

        //注册
        async userRegister(context, user){
            let result = await reqUserRegister(user)
            if(result.code==200){
                return 'ok'
            }else{
                return Promise.reject(new Error('注册超级嘎嘎大失败'))
            }
        },

        //登入
        async userLogin(context, data){
            let result = await reqUserLogin(data)
            //服务器下发TOKEN，用户的唯一标识符
            if(result.code==200){
                context.commit("USERLOGIN", result.data.token)
                //持久化存储token
                sessionStorage.setItem('TOKEN', result.data.token)
                return 'ok'
            }else{
                return Promise.reject( new Error('登入超级嘎嘎大失败'))
            }
        },

        //获取用户信息
        async getUserInfo(context){
            let result = await reqUserInfo()
            if(result.code == 200){
                context.commit('GETUSERINFO', result.data)
                return 'ok'
            }else{
                return Promise.reject(new Error('获取用户信息超级嘎嘎大失败'))
            }
        },

        //退出登入
         async userLogout({commit}){
            //只是向服务器发起一起请求，通知服务器清除token
            let result = await reqLogout()
            if(result.code==200){
                commit('CLEAR')
                return 'ok'
            }else{
                return Promise.reject( new Error('退出超级嘎嘎大失败'))
            }
        }

    },
    mutations: {
        GETCODE(state, code){
            state.code = code  //验证码自动填写了
        },
        USERLOGIN(state, token){
            state.token = token 
        },
        GETUSERINFO(state, userInfo){
            state.userInfo = userInfo 
        },
        CLEAR(state){  //清空仓库中数据
            state.token = ''
            state.userInfo = {}
            sessionStorage.removeItem('TOKEN')
        }
    },
    getters: {},
}